package com.code2roc.fastboot.framework.util;

import com.code2roc.fastboot.framework.config.SystemConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class LogUtil {
    private static SystemConfig systemConfig = BeanUtil.getBean(SystemConfig.class);
    private static String newline = System.getProperty("line.separator");

    public static void writeLog(String logContent) {
        writeLog(logContent, true);
    }

    public static void writeLog(String logContent, boolean dayCreate) {
        writeLog("log_", logContent);
    }

    public static void writeLog(String fileName, String logContent) {
        writeLog(fileName, logContent, true);
    }

    public static void writeLog(String fileName, String logContent, boolean dayCreate) {
        writeLog("", fileName, logContent);
    }

    public static void writeLog(String floderName, String fileName, String logContent) {
        writeLog(floderName, fileName, logContent, true,true);
    }

    public static void writeLog(String floderName, String fileName, String logContent, boolean dayCreate,boolean autoTimeTag) {
        try {
            String path = systemConfig.getLogFilePath();
            if (!StringUtil.isEmpty(floderName)) {
                String[] pathList = floderName.split("/");
                String temp = path;
                for (int i = 0; i < pathList.length; i++) {
                    temp += pathList[i] + "/";
                    File logFolder = new File(temp);
                    if (!logFolder.exists()) {
                        logFolder.mkdirs();
                    }
                }
                path += floderName + "/";
            }
            String filePath = "";
            if (dayCreate) {
                filePath = path + fileName + DateUtil.getDateTagToDay() + ".txt";
            } else {
                filePath = path + fileName + ".txt";
            }
            File logFile = new File(filePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            logFile.setWritable(true);
            FileOutputStream fw = new FileOutputStream(logFile, true);
            Writer out = new OutputStreamWriter(fw, "utf-8");
            if(autoTimeTag){
                out.write(DateUtil.getDateFormatToSecond());
                out.write(newline);
            }
            out.write(logContent);
            out.write(newline);
            out.close();
            fw.flush();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
